package cc.edge2.sns.services;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.arnx.jsonic.JSON;
import cc.edge2.sns.commons.PMF;
import cc.edge2.sns.models.Diary;
import cc.edge2.sns.models.RecentFriendDiary;
import cc.edge2.sns.models.SNSUser;

public class GetRecentFriendDiaryListService {
	public String execute(Map params, SNSUser user) {
		
		List<Map> list = new ArrayList<Map>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(RecentFriendDiary.class);
		query.setFilter("referenceUserId == :referenceUserIdParam");
		query.setRange(0, 10);
		int a = -1;
		try {
			long userId = user.getUserId();
			List<RecentFriendDiary> results = (List<RecentFriendDiary>)query.execute(userId);
			a = results.size();
			for(RecentFriendDiary recentFriendDiary : results) {
				long diaryId = recentFriendDiary.getDiaryId();
				Diary diary = pm.getObjectById(Diary.class, diaryId);
				
				
				Map<String, String> diaryMap = new HashMap<String, String>();
				diaryMap.put("diaryId", "" + diary.getDiaryId());
				diaryMap.put("userId", "" + diary.getUserId());
				diaryMap.put("subject", diary.getSubject());
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd HH:mm");
				diaryMap.put("publishedDate", sdf1.format(diary.getPublishedDate()));
				list.add(diaryMap);
			}
		} catch(JDOObjectNotFoundException e) {
			e.printStackTrace();
		} finally {
			query.closeAll();
		}
		
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> contents = new HashMap<String, Object>();
		Map<String, Object> status = new HashMap<String, Object>();
		status.put("code", "0");
		status.put("message", "success");
		contents.put("recentFriendDiaryList", list);
		contents.put("size", a);
		result.put("status", status);
		result.put("contents", contents);
		String value = JSON.encode(result);
		return value;
	}
}
